import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import '../rfid/rfid_connection.dart';

class BluetoothDeviceItem {
  final String name;
  final String macAddress;
  final int rssi;
  final BluetoothDevice device; // 真实蓝牙对象
  BluetoothDeviceItem(this.name, this.macAddress, this.rssi, this.device);
}

class ScanPage extends StatefulWidget {
  const ScanPage({Key? key}) : super(key: key);

  @override
  State<ScanPage> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  List<BluetoothDeviceItem> _devices = [];
  final RFIDConnection _rfidService = RFIDConnection();
  StreamSubscription? _scanResultsSub;

  @override
  void initState() {
    super.initState();
    _disconnectAndScan();
  }

  @override
  void dispose() {
    _scanResultsSub?.cancel();
    super.dispose();
  }

  Future<void> _disconnectAndScan() async {
    // 先断开已有连接（如果有）
    await _rfidService.disconnect();
    _startScan();
  }

  void _startScan() async {
    _devices.clear();

    // 开始扫描
    await FlutterBluePlus.startScan(
        timeout: const Duration(seconds: 10), androidUsesFineLocation: true);
    _scanResultsSub ??= FlutterBluePlus.scanResults.listen((results) {
      _devices =
          results.where((r) => r.device.platformName.isNotEmpty).map((r) {
        final device = r.device;
        return BluetoothDeviceItem(
          device.platformName,
          device.remoteId.str,
          r.rssi,
          device,
        );
      }).toList();

      // 根据RSSI排序
      _devices.sort((a, b) => b.rssi.compareTo(a.rssi));
      _updateState();
    });
  }

  _updateState() {
    if (mounted) {
      setState(() {});
    }
  }

  void _connectDevice(BluetoothDeviceItem item) async {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('正在连接 ${item.name}...')),
    );
    bool success = await _rfidService.connectDevice(item.device);
    if (success) {
      Navigator.pop(context, item.device);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('连接失败')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 顶部紫色标题栏
          Container(
            color: const Color(0xFF6C2BD7),
            padding:
                const EdgeInsets.only(top: 40, bottom: 16, left: 8, right: 8),
            child: Row(
              children: [
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFF2F2F2),
                    foregroundColor: Colors.black,
                    elevation: 0,
                  ),
                  onPressed: () => Navigator.pop(context),
                  child: const Text('返回'),
                ),
                const Expanded(
                  child: Center(
                    child: Text(
                      '连接设备',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 28,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 2,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 设备列表
          Expanded(
            child: RefreshIndicator(
              onRefresh: () async {
                await _disconnectAndScan();
              },
              child: ListView.separated(
                itemCount: _devices.length,
                separatorBuilder: (_, __) =>
                    Divider(height: 1, color: Colors.grey[300]),
                itemBuilder: (context, idx) {
                  final d = _devices[idx];
                  return ListTile(
                    title: Text(d.name, style: const TextStyle(fontSize: 20)),
                    subtitle: Text(d.macAddress,
                        style: const TextStyle(fontSize: 15)),
                    trailing: Text('RSSI:${d.rssi}',
                        style: const TextStyle(fontSize: 16)),
                    onTap: () => _connectDevice(d),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}
